<template>
    <el-dialog title="分配权限" v-model="visible" width="769px">
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="90px">
            <el-form-item label="权限资源" prop="name">
                <div class="tree-box">
                    <el-tree
                        ref="treeRef"
                        :data="menuTree"
                        show-checkbox
                        node-key="value"
                        :props="{
                            children: 'children',
                            label: 'label',
                            value: 'value',
                        }"
                    ></el-tree>
                </div>
                <!-- :default-expanded-keys="checkKeys"
                :default-checked-keys="checkKeys" -->
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="onCancel" size="default">取 消</el-button>
                <el-button type="primary" @click="onSubmit(ruleFormRef)" size="default">保 存</el-button>
            </span>
        </template>
    </el-dialog>
</template>
<script lang="ts" setup>
import { ref, reactive } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { Role } from '@/api/system/role/types.ts'
import { Option } from '@/api/types.ts'
import { getMenuOptions } from '@/api/system/menu/index.ts'

const visible = ref(false)
const menuTree = ref<Option[]>()
const ruleForm = reactive<Role.Form>({
    status: 1,
    sort: 1,
})
/** 定义表单校验规则 */
const rules = reactive<FormRules<Role.Form>>({
    name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
    code: [{ required: true, message: '请输入角色编码', trigger: 'blur' }],
    dataScope: [{ required: true, message: '请选择数据权限', trigger: 'change' }],
})

/** 关闭弹窗 */
const onCancel = () => {
    visible.value = false
}
/** 保存 */
const ruleFormRef = ref<FormInstance>()
const onSubmit = (formEl: FormInstance | undefined) => {
    if (!formEl) return
}

/** 打开弹窗 */
const openDialog = async (item: Role.Form | undefined) => {
    getMenuTree()
    visible.value = true
}

const getMenuTree = () => {
    getMenuOptions().then((resp: Option[]) => {
        menuTree.value = resp
    })
}

defineExpose({
    openDialog,
})
</script>

<style scoped lang="scss">
.tree-box {
    border: 1px solid var(--prev-border-color-light);
    width: 100%;
    padding: 10px;
    border-radius: 4px;
}
</style>
